package com.chcit.share.generator.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.chcit.share.generator.constants.GeneratorConstant;
import com.chcit.share.generator.factory.IParse;
import com.chcit.share.generator.model.TemplateModel;
import com.chcit.share.generator.vo.GenerationEntity;
import com.chcit.share.generator.vo.TableModel;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * FREEMARK 解析
 *
 * @author liuyang
 */
public class FreeMarkerParseImpl implements IParse {

    private static final Logger LOGGER = LoggerFactory.getLogger(FreeMarkerParseImpl.class);

    private static final StringTemplateLoader resourceLoader = new StringTemplateLoader();

    private static Configuration cfg;

    static {
        try {
            cfg = new Configuration();
            cfg.setTemplateLoader(resourceLoader);
            cfg.setLocale(Locale.CHINA);
            cfg.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    public String parse(GenerationEntity generationEntity, TableModel tableEntity, TemplateModel file) {
        Template t;
        try {

            resourceLoader.putTemplate(file.hashCode() + "_FTL+KEY", file.getTemplateContent());
            t = cfg.getTemplate(file.hashCode() + "_FTL+KEY");
            Writer write = new StringWriter();
            String gen = null;
            String table = null;
            String params = file.getParams();
            JSONObject json = null;
            if (params != null) {
                json = JSONObject.parseObject(params);
            }
            if (json != null) {
                gen = json.getString(GeneratorConstant.GEN_PARAMS);
                table = json.getString(GeneratorConstant.TABLE_DETAIL);

            }
            if (gen == null) {
                gen = IParse.GEN_PARAMS;
            } else {
                json.remove(GeneratorConstant.GEN_PARAMS);
            }
            if (table == null) {
                table = IParse.TABLE_DETAIL;
            } else {
                json.remove(GeneratorConstant.TABLE_DETAIL);
            }
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put(gen, generationEntity);
            paramsMap.put(table, tableEntity);
            if (json != null) {
                for (Map.Entry<String, Object> entry : json.entrySet()) {
                    paramsMap.put(entry.getKey(), entry.getValue());
                }
            }

            t.process(paramsMap, write);

            return write.toString();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return "";
    }

}
